package com.aiit.controller.user;

import com.aiit.config.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.Session;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user/shop")
public class OrderController {
    // 存储 Session 和用户名的映射
    private static final Map<String, Session> SESSION_USER_MAP = new HashMap<>();
    private final WebSocketServer webSocketServer;

    public OrderController(WebSocketServer webSocketServer) {
        this.webSocketServer = webSocketServer;
    }

    // 在用户连接 WebSocket 时调用此方法，将 Session 和用户名关联
    public static void addSession(String username, Session session) {
        SESSION_USER_MAP.put(username, session);
    }

    // 在用户断开 WebSocket 连接时调用此方法，移除关联
    public static void removeSession(String username) {
        SESSION_USER_MAP.remove(username);
    }


    @PostMapping("/remind")
    public String handleRemind(
            @RequestParam Long orderId,
            @RequestParam String
                    username
    ) {
        // 组装催单消息（可自定义格式，如JSON）
        String remindMessage = "订单催单通知：用户[" + username + "]对订单[" + orderId + "]发起催单";

        // 直接广播给所有商家
        webSocketServer
                .broadcastToAll(remindMessage);
        return "催单请求已发送，商家端将实时接收通知";
    }
}